package com.atguigu.gmall.common.config.thread;

import com.atguigu.gmall.common.config.thread.properties.AppThreadProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author tangsy
 * @Description TODO
 * @date 2022/12/5 19:39
 * @Version 1.0
 */
@EnableConfigurationProperties(AppThreadProperties.class)
@Slf4j
@Configuration
public class AppThreadPoolAutoConfiguration {

    @Bean
    public ThreadPoolExecutor coreExecutor(AppThreadProperties threadProperties) {
        return new ThreadPoolExecutor(threadProperties.getCorePoolSize(),
                threadProperties.getMaximumPoolSize(),
                threadProperties.getKeepAliveTime(),
                TimeUnit.MINUTES,
                new LinkedBlockingQueue<>(threadProperties.getWorkQueueSize()),
                new ThreadFactory() {
                    int i = 1;
                    @Override
                    public Thread newThread(Runnable r) {
                        Thread thread = new Thread(r);
                        thread.setName("核心线程["+ i++ +"]");
                        thread.setPriority(10);
                        return thread;
                    }
                },
                new ThreadPoolExecutor.CallerRunsPolicy()
        );
    }

}
